package com.jianyun.jyzs.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;


import com.jianyun.jyzs.bean.TopBrodCastBean;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yangshijun on 2018/9/19.
 */

public class PicsAdapter extends PagerAdapter {

    private List<ImageView> views = new ArrayList<>();
    private Context mContext;

    public PicsAdapter(Context context) {
        mContext = context;
    }

    @Override
    public int getCount() {
        if (views == null) {
            return 0;
        }
        return views.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    public void setData(List<TopBrodCastBean.ImageList> list) {
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                ImageView iv = new ImageView(mContext);
                ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT);
                iv.setLayoutParams(params);
                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                //设置ImageView的属性
                //iv.setImageResource(imgResIds[i]);
                Picasso.with(mContext).load(list.get(i).getImgUrl()).into(iv);
                views.add(iv);
            }
            notifyDataSetChanged();
        }
    }

    public Object getItem(int position) {
        if (position < getCount())
            return views.get(position);
        return null;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        if (position < views.size())
            ((ViewPager) container).removeView(views.get(position));
    }

    @Override
    public int getItemPosition(Object object) {
        return views.indexOf(object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        if (position < views.size()) {
            final ImageView imageView = views.get(position);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onViewPagerListener.onViewPagerClick(position);
                }
            });
            container.addView(imageView);
            return imageView;
        }
        return null;
    }


    public interface OnViewPagerListener {
        void onViewPagerClick(int positioin);
    }

    private OnViewPagerListener onViewPagerListener;

    public void setOnViewPagerClick(OnViewPagerListener onViewPagerClick) {
        this.onViewPagerListener = onViewPagerClick;
    }
}
